import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { getTimeStamp, getToken, } from './auth.js'
const instance = axios.create({
  baseURL: '/api'
})

instance.interceptors.request.use(config => {
  const token = getToken()
  const time = 300 * 60 * 1000
  if (token) {
    const cureentTime = Date.now()
    const tokenTime = getTimeStamp()
    const space = cureentTime - tokenTime
    if (space >= time) {
      store.dispatch('user/logout')
      Message.info('登陆信息已过期,请重新登陆')
      router.push(`/login?_redirect=${window.location.href.split('#')[1]}`)
      return Promise.reject(new Error('token 超时'))
    }
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
},
  error => {
    return Promise.reject(error)
  }
)
instance.interceptors.response.use(
  response => {
    const { data: { message, success } } = response
    if (success) {
      return response.data
    } else {
      Message.error(message)
      return Promise.reject(new Error(message))
    }
  },
  error => {
    if (error.response &&
      error.response.data &&
      error.response.data.code === 10002
    ) {
      store.dispatch('user/logout')
      Message.info('您的账号已过期,请重新登陆')
      router.push(`/login?_redirect=${window.location.href.split('#')[1]}`)
    }
    return Promise.reject(error)
  }
)

export default instance
